'use strict'
const utility = require('utility')

const Controller = require('egg').Controller

class UserController extends Controller {
    async signUp () {

        const { ctx,app } = this
        const { phone,password } = ctx.request.body

        const [isTrue,userLength] = await Promise.all([
            ctx.model.User.findOne({ phone }),
            ctx.model.User.count()
        ])

        if (isTrue) {
            return ctx.body = {
                state:'err',
                errMsg:'此手机号码已被注册!'
            }
        }

        const docs = await ctx.model.User.create({
            phone,
            password:utility.md5(password),
            nickname:`第${userLength + 1}位用户`
        })

        const token = app.jwt.sign({ phone:docs.phone,password:docs.password },
            app.config.jwt.secret,{ expiresIn:'30day' }
        )

        ctx.body = {
            state:'ok',
            data:docs,
            token
        }
    }

    async signIn () {
        const { ctx,app } = this
        const { phone,password } = ctx.request.body
        const docs = await ctx.model.User.findOne({ phone,password:utility.md5(password) })
        if (!docs) return ctx.body = {
            state:'err',
            errMsg:'手机号或者密码错误!'
        }

        const token = app.jwt.sign({ phone:docs.phone,password:docs.password },
            app.config.jwt.secret,{ expiresIn:'30day' }
        )

        ctx.body = {
            state:'ok',
            data:docs,
            token
        }
    }

    async Token () {
        const { ctx,app } = this
        const token = ctx.get('Authorization')
        if (!token) return ctx.body = {
            state:'err'
        }
        try {
            const verify = app.jwt.verify(token,app.config.jwt.secret)
            const docs = await ctx.model.User.findOne(
                { phone:verify.phone,password:verify.password }
            ).select({ password:0 })
            ctx.body = {
                state:'ok',
                data:docs
            }
        } catch (e) {
            ctx.body = {
                state:'err',
                errMsg:'token过期'
            }
        }
    }

    async search () {
        const { ctx } = this
        const { search,page } = ctx.query
        const reg = eval('/' + search + '/')
        const docs = await ctx.model.User
            .find({
                $or:[
                    { nickname:reg },
                    { one_sentence_introduction:reg }
                ]
            })
            .select({ password:0 })
            .skip((page - 1) * 8)
            .limit(8)
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async people () {
        const { ctx } = this
        const { _id } = ctx.query

        try {
            const docs = await ctx.model.User.findOne({ _id }).select({ password:0 })
            ctx.body = {
                state:'ok',
                data:docs
            }
        } catch (e) {
            ctx.body = {
                state:'err',
                data:{}
            }
        }

    }

    async attention () {
        const { ctx } = this
        const { _id,type } = ctx.query
        let docs
        if (type === 'like') {
            [docs] = await Promise.all([
                ctx.model.User.findOneAndUpdate({ _id },{
                    $push:{ fans:ctx.user._id },
                    $inc:{ fans_count:1 }
                },{ new:true }),
                ctx.model.User.update({ _id:ctx.user._id },{ $push:{ attention:_id },$inc:{ attention_count:1 } }),
                ctx.model.Dynamic.create({ user_id:ctx.user._id,type:'关注了用户',attention_user_id:_id }),
                ctx.model.Notice.create({ user_id:_id,type:'关注',text:'关注了你',res_user_id:ctx.user._id })
            ])
            ctx.service.notice.emit(_id)
        }
        if (type === 'noLike') {
            [docs] = await Promise.all([
                ctx.model.User.findOneAndUpdate({ _id },{
                    $pull:{ fans:ctx.user._id },
                    $inc:{ fans_count:-1 }
                },{ new:true }),
                ctx.model.User.update({ _id:ctx.user._id },{ $pull:{ attention:_id },$inc:{ attention_count:-1 } }),
                ctx.model.Dynamic.deleteOne({ user_id:ctx.user._id,type:'关注了用户',attention_user_id:_id })
            ])
        }
        ctx.body = {
            state:'ok',
            data:docs.fans
        }
    }

    async Edit () {
        const { ctx } = this

        const {
            nickname,
            one_sentence_introduction,
            gender,
            introduction,
            avatar
        } = ctx.request.body

        let docs

        if (nickname === ctx.user.nickname) {
            docs = await ctx.model.User.findOneAndUpdate({ _id:ctx.user._id },{
                one_sentence_introduction,
                gender,
                introduction,
                avatar:!avatar.length ? ctx.user.avatar : 'http://cdn.sujie.ink/' + avatar
            },{ new:true })
        } else {
            const count = await ctx.model.User.countDocuments({ $and:[{ nickname },{ _id:{ $ne:ctx.user._id } }] })
            if (count > 0) {
                ctx.body = {
                    state:'err',
                    errMsg:'名字已经被人使用了哦!'
                }
                return
            }
            docs = await ctx.model.User.findOneAndUpdate({ _id:ctx.user._id },{
                    nickname,
                    one_sentence_introduction,
                    gender,
                    introduction,
                    avatar:!avatar.length ? ctx.user.avatar : 'http://cdn.sujie.ink/' + avatar
                },
                { new:true }
            ).select({ password:0 })
        }

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getDynamic () {
        const { ctx } = this

        const { user_id,page } = ctx.query
        const docs = await ctx.model.Dynamic
            .find({ user_id })
            .populate({
                path:'reply_id',
                populate:{ path:'user_id',select:{ password:0 } }
            })
            .populate({
                path:'attention_user_id',
                select:{ avatar:1,nickname:1,fans_count:1,question_count:1,reply_count:1 }
            })
            .populate({
                path:'question_id',
                select:{ content_html:0,content:0 }
            })
            .skip((page - 1) * 8)
            .limit(8)
            .sort({ _id:-1 })

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getDynamicApp () {
        const { ctx } = this

        const { user_id,page } = ctx.query
        const docs = await ctx.model.Dynamic
            .find({ user_id,type:{ $nin:['关注了用户'] } })
            .populate({
                path:'reply_id',
                populate:{ path:'question_id',select:{ title:1 } }
            })
            .populate({
                path:'reply_id',
                populate:{ path:'user_id',select:{ nickname:1 } }
            })
            .populate({
                path:'user_id',
                select:{ password:0 }
            })
            .populate({
                path:'attention_user_id',
                select:{ avatar:1,nickname:1,fans_count:1,question_count:1,reply_count:1 }
            })
            .populate({
                path:'question_id',
                select:{ content_html:0 }
            })
            .skip((page - 1) * 8)
            .limit(8)
            .sort({ _id:-1 })

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getNotice () {
        const { ctx } = this
        const { type,page } = ctx.query

        const docs = await ctx.model.Notice
            .find({ type,user_id:ctx.user._id })
            .populate({
                path:'reply_id',
                select:{ content:1 }
            })
            .populate({
                path:'comment_id',
                select:{ content:1 }
            })
            .populate({
                path:'res_user_id',
                select:{ nickname:1,avatar:1 }
            })
            .populate({
                path:'question_id',
                select:{ title:1 }
            })
            .populate({
                path:'res_comment_id',
                select:{ content:1 }
            })
            .populate({
                path:'res_reply_id',
                select:{ content:1 }
            })
            .skip((page - 1) * 8)
            .limit(8)
            .sort({ see:false,_id:-1 })
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getNoticeDynamic () {
        const { ctx } = this
        const { page } = ctx.query

        const docs = await ctx.model.Dynamic
            .find({
                $or:ctx.user.attention.map(value => ({ user_id:value })),
                $and:[
                    {
                        $or:[
                            { type:'赞同了回答' },{ type:'回答了问题' },{ type:'提出了问题' }
                        ]
                    }
                ]

            })
            .populate({
                path:'reply_id',
                populate:{
                    path:'user_id'
                }
            })
            .populate({
                path:'attention_user_id',
                select:{ avatar:1,nickname:1,fans_count:1,question_count:1,reply_count:1 }
            })
            .populate({
                path:'question_id',
                select:{ content_html:0,content:0 }
            })
            .skip((page - 1) * 8)
            .limit(8)
            .sort({ _id:-1 })
        ctx.body = {
            stat:'ok',
            data:docs
        }


    }

    async getAttentionPeople () {
        const { ctx } = this
        const { _id,page ,type} = ctx.query

        let docs
        if (type === 'all') {
            docs  = await ctx.model.User.find({ fans:{ $in:[_id] } })
        }else {
            docs  = await ctx.model.User.find({ fans:{ $in:[_id] } })
                .skip((page - 1) * 8)
                .limit(8)

        }
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getFansPeople () {
        const { ctx } = this
        const { _id,page } = ctx.query

        const docs = await ctx.model.User.find({ attention:{ $in:[_id] } })
            .skip((page - 1) * 8)
            .limit(8)

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async ClearNotice () {
        const { ctx } = this

        const docs = await ctx.model.Notice.updateMany({
            type:{ $in:['消息','赞同','关注'] },
            user_id:ctx.user._id
        },{ see:true })



        ctx.body = {
            state:'ok',
            data:docs
        }
    }
}

module.exports = UserController
